package com.ruoyi.web.controller.api.payment;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.PublishConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.CharUtil;
import com.ruoyi.common.utils.Test.HttpsService;
import com.ruoyi.common.utils.Test.MD5Util;
import com.ruoyi.common.utils.Test.PrivacyBindBodyAxb;
import com.ruoyi.common.utils.XMLUtil4jdom;
import com.ruoyi.common.utils.redis.RedisUtils;
import com.ruoyi.system.domain.POrder;
import com.ruoyi.system.domain.PStoreOrder;
import com.ruoyi.system.domain.bo.POrderBo;
import com.ruoyi.system.service.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.time.Duration;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/payment/")
public class PaymentController {
    private static Logger logger = LoggerFactory.getLogger(PaymentController.class);

    @Autowired
    private PaymentService paymentService;
    @Autowired
    private IPOrderService iPOrderService;
    @Autowired
    private IPStoreOrderService ipStoreOrderService;
    @Autowired
    private IPVipOrderService ipVipOrderService;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private IPUserBillService ipUserBillService;

    /**
     * <p>统一下单入口</p>
     *
     * @param bo
     * @throws Exception
     */
    @RepeatSubmit()
    @PostMapping(value = "toPay")
    public R<Map<String, String>> toPay(@RequestBody POrderBo bo) throws Exception {
        //回调路径
        String type = "";
        if ("2".equals(bo.getOrderCategory())) {   //创建订单商城
            type = "https://ceshi1.cnshangji.cn/payment/payStoreOrder";
            if(bo.getOrderNo() == null){
                bo.setOrderNo(CharUtil.getRandomNum(16));
                ipStoreOrderService.insertOrderByBo(bo);
            }
            RedisUtils.setCacheObject(PublishConstants.ORDERS_AUTO_CANCEL_KEY + bo.getOrderNo(),bo.getOrderCategory(), Duration.ofMinutes(Constants.ORDER_EXPIRATION));
        } else if ("1".equals(bo.getOrderCategory())){
            type = "https://ceshi1.cnshangji.cn/payment/xcxNotify";
            if(bo.getOrderNo() == null){
                bo.setOrderNo(CharUtil.getRandomNum(16));
                iPOrderService.insertFontByBo(bo);
            }
            RedisUtils.setCacheObject(PublishConstants.ORDER_AUTO_CANCEL_KEY + bo.getOrderNo(),bo.getOrderCategory(), Duration.ofMinutes(Constants.ORDER_EXPIRATION));
        } else if ("0".equals(bo.getOrderCategory())){
            type = "https://ceshi1.cnshangji.cn/payment/pay-ok-test";
            if(bo.getOrderNo() == null){
                bo.setOrderNo(CharUtil.getRandomNum(16));
                iPOrderService.insertTestFontByBo(bo);
            }
            RedisUtils.setCacheObject(PublishConstants.ORDER_AUTO_CANCEL_KEY + bo.getOrderNo(),bo.getOrderCategory(), Duration.ofMinutes(Constants.ORDER_EXPIRATION));
        } else if ("3".equals(bo.getOrderCategory())) {
            type = "https://ceshi1.cnshangji.cn/payment/vipOrder";
            // 开通会员订单
            if(bo.getOrderNo() == null){
                bo.setOrderNo(CharUtil.getRandomNum(16));
                ipVipOrderService.insertOrderByBo(bo);
            }
        } else if ("4".equals(bo.getOrderCategory())) {
            type = "https://ceshi1.cnshangji.cn/payment/recharge";
            if(bo.getOrderNo() == null){
                bo.setOrderNo(CharUtil.getRandomNum(16));
                this.ipUserBillService.insertTestFontByBo(bo);
            }
        }
        Map<String, String> resMap = paymentService.xcxPayment(bo.getOrderNo(), "0.01", bo.getOpenId(),type); //bo.getActualPrice().toString()
        resMap.put("orderNo",bo.getOrderNo());

        return R.ok(resMap);
    }

    @RequestMapping(value = "recharge")
    public void recharge(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        Map<String, Object> map = XMLUtil4jdom.doXMLParse(new String(outputStream.toByteArray(), "utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if ("SUCCESS".equals(returnmsg)) {
                /*__________逻辑__________*/

                this.iSysUserService.recharge(map.get("out_trade_no").toString());

                /*___________END___________*/
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:" + resXml);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        logger.info("【小程序支付回调响应】 响应内容：\n" + resXml);
        response.getWriter().print(resXml);
    }

    @RequestMapping(value = "vipOrder")
    public void vipOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        Map<String, Object> map = XMLUtil4jdom.doXMLParse(new String(outputStream.toByteArray(), "utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if ("SUCCESS".equals(returnmsg)) {
                /*__________逻辑__________*/

                this.ipVipOrderService.askPayOk(map.get("out_trade_no").toString());

                /*___________END___________*/
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:" + resXml);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        logger.info("【小程序支付回调响应】 响应内容：\n" + resXml);
        response.getWriter().print(resXml);
    }

    /**
     * 商城购物车订单支付
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "payStoreOrder")
    public void payStoreOrder(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        Map<String, Object> map = XMLUtil4jdom.doXMLParse(new String(outputStream.toByteArray(), "utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if ("SUCCESS".equals(returnmsg)) {
                /*__________逻辑__________*/

                List<PStoreOrder> orders = this.ipStoreOrderService.orderDetail(map.get("out_trade_no").toString());
                this.ipStoreOrderService.askPayOk(orders);
                //删除key
                RedisUtils.deleteObject(PublishConstants.ORDER_AUTO_CANCEL_KEY + map.get("out_trade_no").toString());

                /*___________END___________*/
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:" + resXml);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        logger.info("【小程序支付回调响应】 响应内容：\n" + resXml);
        response.getWriter().print(resXml);
    }

    /**
     * <p>回调Api</p>
     *
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value = "xcxNotify")
    public void xcxNotify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        Map<String, Object> map = XMLUtil4jdom.doXMLParse(new String(outputStream.toByteArray(), "utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml = "";
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if ("SUCCESS".equals(returnmsg)) {
                /*__________逻辑__________*/

                POrder pOrder = iPOrderService.orderDetail(map.get("out_trade_no").toString());
                iPOrderService.askPayOk(pOrder);
                //删除key
                RedisUtils.deleteObject(PublishConstants.ORDER_AUTO_CANCEL_KEY + map.get("out_trade_no").toString());
                if(!"2".equals(pOrder.getServiceType()) && !"1".equals(pOrder.getServiceType())){
                    //绑定虚拟号
                    deptList(Integer.parseInt(pOrder.getTimeSize()),pOrder.getPhone(),pOrder.getPhones());
                }


                /*___________END___________*/
                    resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:" + resXml);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }
        logger.info("【小程序支付回调响应】 响应内容：\n" + resXml);
        response.getWriter().print(resXml);
    }



    public String  deptList(int time, String phone,String phone1) throws Exception {
        Integer miao = null;
        PrivacyBindBodyAxb bindBodyAxb = new PrivacyBindBodyAxb();
        String str = "13041430152";
        /** AXB模式小号绑定接口地址*/
        String url = "https://101.37.133.245:11008/voice/1.0.0/middleNumberAXB";
        /** 设定绑定的隐私小号*/
        String trumpet = str;
        bindBodyAxb.setMiddleNumber(trumpet);
        /** 设定与该隐私小号绑定的号码A*/
        bindBodyAxb.setBindNumberA(phone1);//专家
        /** 设定与该隐私小号绑定的号码B*/
        bindBodyAxb.setBindNumberB(phone);//用户
        /** 设置是否开启通话录音  1:开启，0:关闭*/
        bindBodyAxb.setCallRec(1);
        /** 设置绑定关系有效时长 ,为空表示绑定关系永久，单位:秒*/
        //计算剩余时间秒 按照当前时间
        bindBodyAxb.setMaxBindingTime(time*60);
        //Date date = new Date();
        //SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        //String format = s.format(new Date());
        ////根据订单号查询预约时间
        //Date gettime = date;
        //if(null==gettime){
        //
        //}else {
        //    String format1 = s.format(gettime);
        //    long b = s.parse(format).getTime();
        //    long a = s.parse(format1).getTime();
        //    int c = (int) ((a - b) / 1000);
        //    bindBodyAxb.setMaxBindingTime(c);
        //}
        /** 设置是否透传主叫的号码到A  0:不透传; 1: 透传，不填默认不透传*/
        bindBodyAxb.setPassthroughCallerToA(1);
        /** 设置是否透传主叫的号码到B  0:不透传; 1: 透传，不填默认不透传*/
        bindBodyAxb.setPassthroughCallerToB(1);
        //提示结束时间
        bindBodyAxb.setMaxCallDuration(1800);
//        /** 设置用于接收呼叫结果的服务地址*/
        bindBodyAxb.setCallbackUrl("https://zhjt.cnshangji.cn/api/front/user/expert/resultsOf");
        /** 获取当前系统时间戳*/
        long timestamp = System.currentTimeMillis();
        /** 生成Base64转码后的参数authorization*/
        String name = 567668+":"+timestamp;
        byte[] bytes = name.getBytes();
        String authorization = Base64.encodeBase64String(bytes);
        /** 生成加密参数sig*/
        String sig = MD5Util.getMD5(567668 + "7d22b0d568ba4fe1ac4e842ec98de9cd" + timestamp);
        /** 生成最终接口访问地址*/
        url = url + "/" + 567668 + "/" + sig;
        String body = JSON.toJSONString(bindBodyAxb);
        /** 调用接口*/
        HttpsService httpsService = new HttpsService();
        String result = httpsService.doPost(url, authorization, body, "UTF-8");
        System.out.println("------------------"+result);
        return str;
    }

    @ApiOperation("测试订单支付成功回调")
    @RequestMapping(value = "pay-ok-test")
    public void payOrderOk(HttpServletRequest request, HttpServletResponse response) throws Exception {
        InputStream inputStream = request.getInputStream();
        //获取请求输入流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len;
        while ((len = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, len);
        }
        outputStream.close();
        inputStream.close();
        Map<String, Object> map = XMLUtil4jdom.doXMLParse(new String(outputStream.toByteArray(), "utf-8"));
        logger.info("【小程序支付回调】 回调数据： \n" + map);
        String resXml;
        String returnCode = (String) map.get("return_code");
        if ("SUCCESS".equalsIgnoreCase(returnCode)) {
            String returnmsg = (String) map.get("result_code");
            if ("SUCCESS".equals(returnmsg)) {
                /*__________逻辑__________*/
                POrder pOrder = iPOrderService.orderFontDetail(map.get("out_trade_no").toString());
                iPOrderService.testPayOk(pOrder);
                //删除key
                RedisUtils.deleteObject(PublishConstants.ORDER_AUTO_CANCEL_KEY + map.get("out_trade_no").toString());
                /*___________END___________*/
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                    + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml>";
            } else {
                resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
                logger.info("支付失败:" + resXml);
            }
        } else {
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                + "<return_msg><![CDATA[报文为空]></return_msg>" + "</xml>";
            logger.info("【订单支付失败】");
        }

        logger.info("【小程序支付回调响应】 响应内容：\n" + resXml);
        response.getWriter().print(resXml);
    }
}
